package com.fly.flowdemo.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created with Android Studio.
 * Package_Name：com.fly.flowdemo.view
 * Project_Name：FlowDemo
 * User：郭鹏飞
 * Date：2015/12/9
 * Email：love518420@foxmail.com
 * Description：
 */
public class SingleButtonFlowLayout extends ButtonFlowLayout {

    private OnItemClickListener listener;

    public SingleButtonFlowLayout(Context context) {
        this(context, null);
    }

    public SingleButtonFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SingleButtonFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setLabels(String[] labels) {
        super.setLabels(labels);
        // 设置默认第一个被选中
        setDefaultChoose(0);
    }

    @Override
    protected void dealWithClickEvent(View view, int position) {
        // 清空选择
        clearChooseStatus();
        // 设置当前选中
        view.setBackgroundResource(selectedResId);
        if (listener != null) {
            listener.onItemClick(view, position);
        }
    }

    /**
     * 设置默认选中
     *
     * @param position 位置 设置为-1表示全部不做选中状态
     */
    public void setDefaultChoose(int position) {
        if (getChildCount() <= 0) {
            throw new NullPointerException("没有子view");
        }
        if ((position != -1 && position < 0) || position >= getChildCount()) {
            throw new IllegalArgumentException("位置非法");
        }
        // 清空选中状态
        clearChooseStatus();
        if (position != -1) {
            // 得到当前位置的View 设置选中状态
            View child = getChildAt(position);
            child.setBackgroundResource(selectedResId);
        }
    }

    /**
     * 为每一个item添加点击事件
     *
     * @param listener 点击事件回调
     */
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        /**
         * 点击事件的回调
         *
         * @param view     当前被点击的view
         * @param position 当前被点击的view的位置
         */
        void onItemClick(View view, int position);
    }

}
